import x from '@/common/base.js';
export default {
    install(Vue){

        //全局混入
        Vue.mixin({
            data(){
                return {
                    rootHost : "https://app.quick365.cn/",
                    appHost : "https://kyy.quick365.cn/",
                    appTitle:'精绝壁纸',
                    appName:'jjbz_quick_huawei',
                    appVersion:'1',
                    isProduct:0,
                    isAd:0,
                    isAdUni:0,
                    currentPage:"",
                    // 通用广告
                    common_ad:{ad_id:0,from:'',ad_type:''},
                    // 插屏广告
                    cp_ad:{ad_id:0,from:''},
                    // 激励视频广告
                    reward_ad:{ad_id:0,from:''},
                    // 微信激励视频广告
                    videoAd: null,
                    adTimer:null,
                };
            },
            onLoad:function(){
                this.x_getUserToken();
                this.x_getPage();
            },
            onShow() {
            },
            methods:{
                x_getPage(){
                    var t =this;
                    var pages = getCurrentPages() // 获取栈实例
                   if(pages[pages.length - 1]['route']){
                       var currentPageObj = pages[pages.length - 1];
                       var url = currentPageObj['route'];
                       t.currentPage =  url;
                       const options = currentPageObj.options;
                       let params = '';
                       for (let key in options) {
                           params += `${key}=${options[key]}&`;
                       }
                       if (params.length > 0) {
                           params = '?' + params.substring(0, params.length - 1); // 移除最后一个"&"
                       }
                       var fullPath = '/'+url + params;
                       var pagesList = t.xCacheGet('pagesList');
                       if(!pagesList){
                           pagesList = [];
                       }
                       if(pagesList.length > 0){
                           let lastElement = pagesList[pagesList.length-1];
                           if(lastElement !== fullPath){
                               pagesList.push(fullPath);
                           }
                       }else{
                           pagesList.push(fullPath);
                       }
                       t.xCacheSet('pagesList',pagesList);
                   }
                },
                //请求
                x_request(url,param,call,isStatic){
                    var t =this;
                    if(!param) param = {};
                    if(!isStatic) isStatic = 0;
                    var requestParam = {
                        uuid: t.x_getUserToken(),
                        app_name: t.appName,
                        current_page:t.currentPage,
                        app_version:t.appVersion,
                        utime:t.xCacheGet('utime')
                    };
                    requestParam = Object.assign(requestParam,param)
                    uni.request({
                        url: t.rootHost + url,
                        data: x.authParam(requestParam)
                    }).then(res=>{
                        res = res.data;
                        if (res.code === 1) {
                            t.isProduct = res.status;
                            t.isAd = res.is_ad;
                            t.isAdUni = res.is_ad_uni;
                        }else{
                            if(isStatic === 0){
                                if(res.code === 0){
                                    uni.showToast({title: res.info, icon: 'error', duration: 2000})
                                }
                                if(!res.info){
                                    uni.showToast({title: res.info, icon: 'error', duration: 2000})
                                }
                            }
                        }
                        if(call){
                            call(t,res);
                        }
                    });
                },
                //请求
                x_app_request(url,param,call,isStatic){
                    var t =this;
                    if(!param) param = {};
                    if(!isStatic) isStatic = 0;
                    var requestParam = {
                        uuid: t.x_getUserToken(),
                        app_name: t.appName,
                        current_page:t.currentPage,
                        app_version:t.appVersion,
                        utime:t.xCacheGet('utime')
                    };
                    requestParam = Object.assign(requestParam,param)
                    uni.request({
                        url: t.appHost + url,
                        data: x.authParam(requestParam)
                    }).then(res=>{
                        res = res.data;
                        if(call){
                            call(t,res);
                        }
                    });
                },
                // 页面跳转
                x_redirect(path,appId){
                    // uni.redirectTo({
                    //     url: path
                    // });
                    if(appId){
                        wx.navigateToMiniProgram({
                            appId: appId,
                            path: path,
                            envVersion: 'release',//上线版，开发版develop
                            success(res) {
                                console.log('跳转成功')
                            }
                        })
                    }
                    var pages = getCurrentPages()
                    if(pages.length >= 10){
                        uni.redirectTo({
                            url: path
                        });
                    }else{
                        uni.navigateTo({
                            url: path
                        });
                    }
                },
                x_back(){
                    uni.navigateBack()
                },
                x_config(){
                    // this.x_request('api/config/index/',{},function(t,res){
                    //     if (res.code === 1) {
                    //         t.isProduct = res.status;
                    //         t.isAd = res.is_ad;
                    //     }
                    // });
                },
                x_alert(type,title,call,content){
                    if(!content) content = '';
                    this.$refs.xpop.dialogToggle(this,type,title,content,call);
                },
                x_tips(type,title){
                    this.$refs.xpop.messageToggle(this,type,title);
                },
                x_getUserToken() {
                    return x.getUserToken(this)
                },
                xCacheSet(key,data,outTime){
                    outTime = outTime?outTime:0;
                    let isExpire = outTime !== 0;
                    var timestamp = Date.now();
                    var cacheData = {isExpire:isExpire,expire:timestamp + outTime*1000,data:data};
                    try {
                        uni.setStorageSync(key, cacheData);
                        return true;
                    } catch (e) {
                        return false;
                    }
                },
                xCacheGet(key){
                    try {
                        const value = uni.getStorageSync(key);
                        if (value) {
                            if(!value.isExpire){
                                return value.data;
                            }else{
                                var timestamp = Date.now();
                                if(value.expire - timestamp <= 0){
                                    return false;
                                }else{
                                    return value.data;
                                }
                            }
                        }
                    } catch (e) {
                        return false;
                    }
                },
                // 获取广告通用
                x_get_ad(ad_type){
                    this.x_request('api/config/ad/',{ad_type:ad_type},function(t,res){
                        if(res.code === 1){
                            if(ad_type === 'common'){
                                t.common_ad = res.data;
                            }else if(ad_type === 'cp'){
                                t.cp_ad = res.data;
                            }else if(ad_type === 'reward'){
                                t.reward_ad = res.data;
                            }

                        }
                    });
                },
                // 插屏广告
                cpAd() {
                    var t = this;
                    t.x_get_ad('cp');
                    setTimeout(function () {
                        if(t.cp_ad.ad_id && t.cp_ad.from){
                            if(t.cp_ad.from === 'wx'){
                                t.cpAdWechat(t.cp_ad.ad_id);
                            }else if(t.cp_ad.from === 'uni'){
                                t.cpAdUni(t.cp_ad.ad_id);
                            }
                        }
                    }, 1000)
                },
                cpAdWechat(ad_id){
                    // 在页面中定义插屏广告
                    let interstitialAd = null
                    // 在页面onLoad回调事件中创建插屏广告实例
                    if (wx.createInterstitialAd) {
                        interstitialAd = wx.createInterstitialAd({
                            adUnitId: ad_id
                        })
                        interstitialAd.onLoad(() => {
                        })
                        interstitialAd.onError((err) => {
                        })
                        interstitialAd.onClose(() => {
                        })
                    }
                    // 在适合的场景显示插屏广告
                    if (interstitialAd) {
                        interstitialAd.show().catch((err) => {
                            console.error(err)
                        })
                    }
                },
                // uni 插屏
                cpAdUni(ad_id){
                    var t = this;
                    t.$refs.adInterstitial.show();
                    t.x_request('api/ad/record/',{position_id:ad_id,ad_platform:'uni',type:'cp'})
                },

                // 激励视频广告
                initRewardAd() {
                    var t = this;
                    t.x_get_ad('reward');
                    setTimeout(function () {
                        if(t.reward_ad.ad_id && t.reward_ad.from){
                            if(t.reward_ad.from === 'wx'){
                                t.initAdRewardWechat(t.reward_ad.ad_id);
                            }else if(t.reward_ad.from === 'uni'){
                                t.initRewardAdUni(t.reward_ad.ad_id);
                            }
                        }
                    }, 1000)
                },
                initAdRewardWechat(ad_id){
                    console.log("初始化激励",ad_id);
                    // 初始化微信广告
                    if (wx.createRewardedVideoAd) {
                        this.videoAd = wx.createRewardedVideoAd({
                            adUnitId: ad_id
                        })
                        this.videoAd.onLoad(() => {
                        })
                        this.videoAd.onError((err) => {
                            console.log(err);
                        })
                        this.videoAd.onClose((res) => {
                            // 用户点击了【关闭广告】按钮
                            if (res && res.isEnded) {
                                this.addTimes();
                            } else {
                                // 播放中途退出，不下发游戏奖励
                            }
                        })
                    }
                },
                initRewardAdUni(ad_id){
                    this.$refs.adRewardedVideo.load();
                },
                userCoinsRecord(coins,remark){
                    var t = this;
                    var userInfo = x.getUserInfo(t);
                    coins = parseInt(coins);
                    userInfo.coins = userInfo.coins + coins;
                    if(userInfo.coins < 50000){
                        x.setUserInfo(t,userInfo);
                        var xCoinsRecord = t.xCacheGet('xCoinsRecord');
                        xCoinsRecord = xCoinsRecord?xCoinsRecord:[];
                        var time = Date.now();
                        var row = {coins:coins,remark:remark,time:time};
                        xCoinsRecord.push(row)
                        t.xCacheSet('xCoinsRecord',xCoinsRecord);
                    }

                }
            }
        });
        Vue.prototype.hello = ()=>{
            alert("你好啊");
        }
    }
}
